/*
 * Copyright (C) 2011 AaDevelopment Team.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.aa.AaCamera_Host_Demo;


import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.view.View;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import static com.aa.AaCamera_Host_Demo.HostUtil.*; //import constants

public class AaCamera_Host_Demo extends Activity 
{

	HostUtil mHostUtil;

	static final int STATE_INIT 					= 0x1;
	static final int STATE_FINISH 					= 0x2;
	static final int STATE_CHECK_AACAMERA_PACKAGE 	= 0x3;
	static final int STATE_DO_COUNT                 = 0x4;

	int mNextState = STATE_INIT;

	TextView mTextView;
	ScrollView  mSv;

	//    PackageManager mPm_AA;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main);
		mTextView =(TextView)findViewById(R.id.textView);
		mSv       =(ScrollView)findViewById(R.id.sv);
		mHostUtil = new HostUtil( getPackageManager());

		addText (" This code will work without any changes starting Android OS 1.6 \n");

		if(Build.MANUFACTURER.equals("unknown")) 
		{
			// Emulator
			addText ("\n\t AaCamera_Host_Demo unable to run on emulator. Use real Android device.");
			addText ("\n\t Press Next to FINISH ");
			mNextState = STATE_FINISH;
		}
		else
			addText ("\n\t Press Next to continue");
	}
	//-
	void hostDemo()   
	{
		switch (mNextState)
		{
		case STATE_INIT://verify Android version, Network connectivity, Front Camera 
			addText("\n Verify Android OS version..........");
			if (verifyAndroidOSverion() )  addText ("OK");
			else	
			{
				addText ("..ERROR \n AaCamera is required at least Android OS 2.3.1");
				addText ("\n\t Press Next to FINISH ");
				mNextState = STATE_FINISH;
				break;
			}
			//-
			addText("\n Verify front camera..........");
			if (mHostUtil.hasFrontCamera ())  addText ("OK");
			else 
			{
				addText ("ERROR \n Front camera does not found");
				addText ("\n\t Press Next to FINISH ");
				mNextState = STATE_FINISH;
				break;
			}

			mNextState = STATE_CHECK_AACAMERA_PACKAGE;
			//break;  no break goes to next stage

		case STATE_CHECK_AACAMERA_PACKAGE:

			addText("\n Check compatible AaCamera Package...........");	
			if (mHostUtil.isAaCameraPackageInstalled() ) 
			{
				addText ("OK Installed");
				addText ("\n\t Press Next to do counting with  AaCamera");
				mNextState = STATE_DO_COUNT;
			}	            
			else 
			{
				addText ("Correctable ERROR \n Not Installed ");
				addText ("\n\t Starting dowload from market");
				addText ("\n\t Press Next to Check package again ");
				mHostUtil.downloadFromMarket( getApplicationContext());    			
			}

			break;

		case STATE_DO_COUNT:
			prepareIntentAndStartAaCameraActivity();
			break;

		}//switch

	}
	//-
	void addText(String str)
	{

		mTextView.append(str);
		mSv.post(new Runnable() { 
			public void run() { 
				mSv.fullScroll(ScrollView.FOCUS_DOWN); 
			} 
		}); 

	}
	//-
	void printFlags(int  flags)
	{
		addText ("Flags used:\n");
		for (Flags f : Flags.values())
		{
			if ( (f.get() & flags) > 0)
				addText ("  " + f + "\n");
		}

	}

	//- 
	public  void toast(String s)
	{
		CharSequence text = s;
		Toast toast = Toast.makeText(getBaseContext(), text, Toast.LENGTH_LONG);
		toast.show();
	}
	//-
	public void onClickExit(View v) 
	{
		finish();
	};
	//-
	public void onClick(View v) 
	{
		if (mNextState == STATE_FINISH) finish();
		hostDemo();

	};
	/////////////////////// RECOMMENDED ROUTINES AS IS //////////////////////////////     
	@Override
	protected void onResume() 
	//NOTE:  ////////////////////////////////////////////////////////////////////////////////////
	//	    There is no way to know when and how will be finished download from market.
	//	    Possible onResume if (mNextState == STATE_CHECK_AACAMERA_PACKAGE)
	//NOTE:  ////////////////////////////////////////////////////////////////////////////////////  			
	//		Possible reasons for download failure:
	//			-no Internet connectivity
	//			-user cancel download
	//			-user does not accept application Permissions.
	//			
	//			Recommended explain to user
	//			-enable Internet connectivity
	//			-initiate download process
	//			-accept AaCamera permissions
	//			and try download process
	/////////////////////////////////////////////////////////////////////////////////////////////
	{
		super.onResume(); 
		//Check that download completed
		if (mNextState == STATE_CHECK_AACAMERA_PACKAGE) hostDemo();
	}
	//-    
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
		addText ("\n\n nActivityResult()\n");
		super.onActivityResult(requestCode, resultCode, data); 
		if (requestCode == DO_CAMERA_COUNT_REQUEST_CODE)
		{
			switch (resultCode)
			{
			case RESULT_OK:
				addText ("\n RESULT_OK");
				int outFlags = data.getIntExtra (EXTRA_OU_INT_FLAGS, 0);
				printFlags (outFlags);

				//print active zone upon exit
				Rect outRect = (Rect) data.getParcelableExtra(EXTRA_OU_RECT_ACTIVE_ZONE);
				addText ("\n OU_RECT_ACTIVE_ZONE =" + outRect);

				int countDone = data.getIntExtra (EXTRA_OU_INT_EXERCISE_COUNT_DONE, 0); 
				addText("\n EXTRA_OU_INT_EXERCISE_COUNT_DONE....." + countDone);
				addText("\n Due to small procent of false counting is recommended " +
						"let user to edit COUNT_DONE before register it") ;		   


				int timeDone = data.getIntExtra (EXTRA_OU_INT_EXERCISE_TIME_DONE_SEC, 1); 
				addText("\n EXTRA_OU_INT_EXERCISE_TIME_DONE_SEC....." + timeDone);
				addText("\n User could spend more  time on Reset or prepare proper place for camera. " +
						"Here reported clean time to calculate real exercise rate   ") ;		        	   

				break;

			case RESULT_CANCELED	 :
				addText ("\n RESULT_CANCELED");
				break;

			}//switch
		}
	}    
	//-
	public  boolean prepareIntentAndStartAaCameraActivity ()
	{
		boolean res = true;

		addText("\n\n prepareIntentAndStartAaCameraActivity() \n");

		// Set custom title message
		String title = "Host demo title" ;
		addText ("\n Set custom title=" + title);
		mAaCameraIntent.putExtra(Intent.EXTRA_TITLE, "Host demo title");

		// Set In flags
		int inFlags = Flags.FLAG_IN_COUNT_DOWN.get()
				// | Flags.FLAG_IN_SILENT.get() 
				;        
		printFlags( inFlags);        
		mAaCameraIntent.putExtra(EXTRA_IN_INT_FLAGS, inFlags );

		// Set Active zone RECT_ACTIVE_ZONE 
		Rect rect = new Rect(0,0, 75,55);
		addText ("\n Set active zone=" + rect);
		mAaCameraIntent.putExtra(EXTRA_IN_RECT_ACTIVE_ZONE, rect );

		// Set EXERCISE_MAX_COUNT   
		addText ("\n Set EXERCISE_MAX_COUNT=26");
		mAaCameraIntent.putExtra(EXTRA_IN_INT_EXERCISE_MAX_COUNT, 26 );

		// Set EXERCISE_MAX_TIME_SEC  
		int maxTimeSec = 3*60 ;
		addText ("\n Set EXERCISE_MAX_TIME_SEC = " + maxTimeSec);
		mAaCameraIntent.putExtra(EXTRA_IN_INT_EXERCISE_MAX_TIME_SEC, maxTimeSec );


		try{
			startActivityForResult(mAaCameraIntent, DO_CAMERA_COUNT_REQUEST_CODE);
		}

		catch (android.content.ActivityNotFoundException e)
		{
			res = false;
		}

		return res;
	}
}//End Of Class
//End Of File